package com.zhoujing.springsecurity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhoujing.springsecurity.mapper.SysUserMapper;
import com.zhoujing.springsecurity.pojo.LoginUser;
import com.zhoujing.springsecurity.pojo.SysUser;
import com.zhoujing.springsecurity.service.SysRoleMenuService;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author 周敬
 * @version 1.0
 * @packageName com.zhoujing.springsecurity.service.impl
 * @fileName UserDetailsImpl
 * @createTime 2022/3/7-15:51-星期一
 * @lastModify 2022/3/7-15:51-星期一
 */
@Service
public class UserDetailsImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMenuService roleMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUserName,username);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户名或密码输入错误");
        }

        List<String> permsByUser = roleMenuService.getPermsByUser(sysUser.getId());
        return new LoginUser(sysUser,permsByUser);
    }
}
